package org.csu.mypetstoreapi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.codec.digest.DigestUtils;
import org.csu.mypetstoreapi.common.CommonResponse;
import org.csu.mypetstoreapi.entity.*;
import org.csu.mypetstoreapi.persistence.*;
import org.csu.mypetstoreapi.service.AccountService;
import org.csu.mypetstoreapi.vo.AccountVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/account")
@CrossOrigin
@Validated
public class AccountController {

//    @Autowired
//    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private ProfileMapper profileMapper;

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private AccountService accountService;
    @Autowired
    private SignOnMapper signOnMapper;

    @GetMapping("/myAccountForm/{username}")
    @ResponseBody
    public CommonResponse<AccountVO> myAccountForm(@PathVariable("username") String username){
        return accountService.getAccount(username);
    }


    //用户登录
    @PostMapping("/login")
    @ResponseBody
    public CommonResponse<AccountVO> login(HttpServletRequest request, @RequestParam("code") String code,
       @Validated @ModelAttribute User user,
         BindingResult bindingResult,
            Model model, HttpSession session){

        System.out.println("用户名、密码和验证码为："+user.getUsername()+","+user.getPassword()+","+code);
        //登陆失败
        //1、用户名、密码输入格式不正确
        System.out.println(bindingResult.getAllErrors());
        StringBuilder validationErrorMsg = new StringBuilder();
        if(bindingResult.hasErrors()){
            for (ObjectError error: bindingResult.getAllErrors()){
                validationErrorMsg.append(error.getDefaultMessage());
                validationErrorMsg.append(",");
            }
            model.addAttribute("loginMsg",validationErrorMsg.subSequence(0,validationErrorMsg.length()-1));
            return accountService.getAccount(user.getUsername(), user.getPassword());
        }

        //2、验证码不正确
        session = request.getSession();
        String emailCode = (String) session.getAttribute("email_code");
        // 验证码比对
        System.out.println("输入code="+code+",正确code="+emailCode);
        if (!StringUtils.equals(code, emailCode)) {
            request.setAttribute("error", "验证码错误");
            model.addAttribute("loginMsg","验证码不正确");
           return CommonResponse.createForError("验证码错误");
        }

        //3、数据库查询失败
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",user.getUsername());
        User loginUser = userMapper.selectOne(userQueryWrapper);
        System.out.println(loginUser);
        if(loginUser==null){
            model.addAttribute("loginMsg","用户名不存在");
            return CommonResponse.createForError("用户名不存在");
        }

        else{//4、登陆成功
            System.out.println("登陆成功......");
            CommonResponse<AccountVO> response = accountService.getAccount(user.getUsername(), user.getPassword());
            session.setAttribute("login_account", response.getData());
            session.setAttribute("loginUser",user);
            return response;
        }

    }



    //用户注册
    @PostMapping("/register")
    @ResponseBody
    public CommonResponse<AccountVO> register(HttpServletRequest request,
                           @RequestParam("code") String code,
                           @Validated @ModelAttribute Account registerAccount,
                           BindingResult bindingResult//一定要跟在@Validated的后面！
                           ){
        System.out.println("用户名、密码和验证码为："+registerAccount.getUsername()+","+registerAccount.getPassword()+","+code);

        //用户名和密码输入格式问题
//        System.out.println(bindingResult.toString());
        StringBuilder validationErrorMsg = new StringBuilder();
        if(bindingResult.hasErrors()){
            for (ObjectError error: bindingResult.getAllErrors()){
                validationErrorMsg.append(error.getDefaultMessage());
                validationErrorMsg.append(",");
            }
            return CommonResponse.createForError(validationErrorMsg.subSequence(0,validationErrorMsg.length()-1).toString());
        }
        //验证码正确与否
        HttpSession session = request.getSession();
        String emailCode = (String) session.getAttribute("email_code");
        System.out.println(session.getId());
        // 验证码比对
        System.out.println("输入code="+code+",正确code="+emailCode);
        if (!StringUtils.equals(code, emailCode)) {
            request.setAttribute("error", "验证码错误");
            return CommonResponse.createForError("验证码错误");
        }

        //查询数据库该用户名是否存在
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",registerAccount.getUsername());
        User newUser = userMapper.selectOne(userQueryWrapper);
        System.out.println(newUser);
        //存在则返回当前页面
        if (newUser!=null){
            return CommonResponse.createForError("用户名已存在");
        }
        //若不存在则添加用户：signon、userinfo、account、profile
        else{
            User registerUser = registerAccount.initUser();
            Profile registerProfile = registerAccount.initProfile();
            //密码使用md5数据加密
            registerAccount.setPassword(DigestUtils.md5Hex(registerAccount.getPassword()));
            System.out.println(registerAccount.getPassword());
            SignOn signOn=new SignOn();
            signOn.setPassword(registerAccount.getPassword());
            signOn.setUsername(registerAccount.getUsername());
            signOnMapper.insert(signOn);
            accountMapper.insert(registerAccount);
            userMapper.insert(registerUser);
            profileMapper.insert(registerProfile);
            CommonResponse<AccountVO> response = accountService.getAccount(registerAccount.getUsername(), registerAccount.getPassword());
            System.out.println(registerAccount.getUsername()+ " 用户注册成功......");
            return response;
        }
    }
}
